package fr.inserm.u915.tabixserver;

import java.io.IOException;
import java.io.OutputStream;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

public abstract class AbstractXmlHandler extends Handler
	{
	private XMLStreamWriter w;
	protected String encoding;
	protected String stylesheetURI=null;
	protected AbstractXmlHandler(OutputStream out,String encoding) throws IOException
		{
		XMLOutputFactory xmlfactory= XMLOutputFactory.newInstance();
		try
			{
			this.encoding=(encoding==null?"UTF-8":encoding);
			this.w= xmlfactory.createXMLStreamWriter(out,encoding);
			}
		catch (XMLStreamException e)
			{
			throw new IOException(e);
			}
		}
	
	protected XMLStreamWriter getWriter()
		{
		return this.w;
		}
	
	public void setStylesheetURI(String stylesheetURI)
		{
		this.stylesheetURI = stylesheetURI;
		}
	
	@Override
	public void writeStartDocument() throws IOException
		{
		try
			{
			this.w.writeStartDocument(this.encoding, "1.0");
			if(this.stylesheetURI!=null)
				{
				w.writeProcessingInstruction("xml-stylesheet",
					" href=\""+
					this.stylesheetURI+
					"\" type=\"text/xsl\""
					);
				}
			}
		catch (XMLStreamException e)
			{
			throw new IOException(e);
			}
		}
	@Override
	public void writeEndDocument() throws IOException
		{
		try
			{
			this.w.writeEndDocument();
			this.w.flush();
			this.w.close();
			}
		catch (XMLStreamException e)
			{
			throw new IOException(e);
			}
		}
	}
